import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  winAttr: async (): Promise<Wx.Mawby.WinParam> => {
    return ipcRenderer.invoke('win-attr')
  },
  getAsset: async (fn: string): Promise<string> => {
    return ipcRenderer.invoke('get-asset', fn)
  },
  getAssets: async (fns: Map<string, string>): Promise<Map<string, string>> => {
    return ipcRenderer.invoke('get-assets', fns)
  },
  getDiyAsset: async (pathstr: string, fn: string): Promise<string> => {
    return ipcRenderer.invoke('get-diy-asset', pathstr, fn)
  },
  getResources: async (fns: Map<string, string>): Promise<Map<string, string>> => {
    return ipcRenderer.invoke('get-resources', fns)
  },
  getFonts: async (fn: string): Promise<ArrayBuffer> => {
    return ipcRenderer.invoke('get-fonts', fn)
  },
  jsonAsset: async (fn: string): Promise<Record<string, unknown>> => {
    return ipcRenderer.invoke('json-asset', fn)
  },
  assetsDataUrl: async (fn: string): Promise<string> => {
    return ipcRenderer.invoke('assets-data-url', fn)
  },
  diyPortfolio: async (): Promise<Map<string, Wx.Card.Data[]>> => {
    return ipcRenderer.invoke('diy-portfolio')
  },
  savePortfolio: async (data: Wx.Card.Data): Promise<Wx.Mawby.Request> => {
    return ipcRenderer.invoke('save-portfolio', data)
  },
  renamePortfolio: async (data: Wx.Card.Data): Promise<Wx.Mawby.Request> => {
    return ipcRenderer.invoke('rename-portfolio', data)
  },
  readDiyData: async (): Promise<Wx.Mawby.Request> => {
    return ipcRenderer.invoke('read-diy-data')
  },
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch {
    //
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
